var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const jsdom = require("jsdom");
const {JSDOM} = jsdom;
const {Script} = require("vm");

app.use(bodyParser.urlencoded({
    parameterLimit: 50000,
    limit: '50mb',
    extended: false

}));

// app.get('/', function (req, res) {
//     res.send('Hello World');
// })


// 通用性
app.post('/api/jsdom_get_param', function (req, res) {
    const resp = {};
    try {
        var html = req.body.html.toString();            //
        var html_script = req.body.html_script.toString();   // 执行js
        var rlist = eval(req.body.rlist.toString());   // 返回结果 window.

        plugins = [];
        var options = {
            // referrer: "",
            userAgent: "Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/74.0.3729.169 Safari/537.36",
            resources: "usable",    // 假如你想通过<script src="">来执行外部脚本，你需要确保已经加载了它们。为此，请添加选项resources:"usable"
            runScripts: "dangerously",
            // url: 'https://www.sos.state.co.us/',
            url: "http://localhost/",
            beforeParse(window) {
                window.screen = {
                    width: 2560,
                    availHeight: 1400,
                    availLeft: 0,
                    availTop: 0,
                    availWidth: 2560,
                    colorDepth: 24,
                    height: 1440,
                    pixelDepth: 24,
                    orientation: {
                        angle: 0,
                        type: "landscape-primary"
                    }
                };
                window.getjs = () => {
                    return window.js
                };
                window.navigator.languages = ["zh-CN", "zh"];
                window.navigator.plugins = plugins
                window.navigator.getBattery = () => {
                    return {
                        'charging': true,
                        'chargingTime': 0,
                        'dischargingTime': Infinity,
                        'level': 1,
                    }
                };
                window.navigator.mimeTypes = [{"type": "application/360softmgrplugin"}, {"type": "application/aliedit"}, {"type": "application/asx"}, {"type": "application/bd-npyunwebdetect-plugin"}, {"type": "application/cenroll.cenroll.version.1"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/futuresplash"}, {"type": "application/hwepass2001.installepass2001"}, {"type": "application/hwpta.itrushwpta"}, {"type": "application/hwwdkey.installwdkey"}, {"type": "application/itrusenroll.certenroll.version.1"}, {"type": "application/mozilla-npqihooquicklogin"}, {"type": "application/npalicdo"}, {"type": "application/npalissologin"}, {"type": "application/npqqwebgame"}, {"type": "application/nptxsso"}, {"type": "application/npxf-qqminidl"}, {"type": "application/npxluser_plugin"}, {"type": "application/pdf"}, {"type": "application/pta.itruspta.version.1"}, {"type": "application/qscall-plugin"}]
                window.navigator.connection = {
                    'downlink': 10,
                    'effectiveType': '4g',
                    'rtt': 50,
                    'saveData': false
                };
                window.Infinity = Infinity;
            },
            // virtualConsole: new jsdom.VirtualConsole(),
            cookieJar: new jsdom.CookieJar(),
            pretendToBeVisual: true,
        };

        const dom = (new JSDOM(html, options));
        const window = dom.window;

        resp.status = 1;

        if (html_script != '') {
            const s = new Script(html_script);
            dom.runVMScript(s);
        }

        window.addEventListener('load', function () {       // 加载完
            /* Only two script nodes in the DOM */
            console.log("ready to roll!");

            for (var i = 0; i < rlist.length; i++) {
                key = rlist[i]
                resp[key] = window[key];
                // console.log(key + ":" + window[key])
            }
            res.send(JSON.stringify(resp));
        });
        // window.close();
    } catch (err) {
        resp.status = 2;
        resp.message = err;
    } finally {
        // res.send(JSON.stringify(resp));
    }
})

var server = app.listen(5592, function () {

    var host = server.address().address
    var port = server.address().port

    console.log("应用实例，访问地址为 http://%s:%s", host, port)
})